// pages/confirm-order/confirm-order.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        deliveryType: 'pickup', // pickup: 自取, delivery: 配送
        showAddressModal: false,
        selectedAddress: null,
        selectedCoupon: null,
        remark: '',
        deliveryType: 'pickup', // 默认选自取
        deliveryFee: 0.1,
        // selectSelf: function () {
        //     this.setData({
        //         deliveryType: 'pickup'
        //     });
        // },

        // 店铺信息
        shopInfo: {
            name: '小鲜谷奶皮子手工酸奶酪',
            address: '吉林省白山市长白朝鲜族自治县长白镇粮食车队综合楼门市房一楼2号'
        },

        // 商品信息
        products: [
            {
                id: 1,
                name: '奶皮子手工酸奶酪（原味）',
                price: 7.90,
                quantity: 1,
                spec: ''
            },
            {
                id: 2,
                name: '奶皮子手工酸奶酪（草莓）',
                price: 8.90,
                quantity: 1,
                spec: ''
            }
        ],

        // 地址列表
        addressList: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.setNavigationBarTitle({
            title: '确认订单'
        })
        // 从上一页传递数据
        console.log(options.products)
        if (options.products) {
            const products = JSON.parse(options.products);
            this.setData({ products });
        }
        if (options.deliveryType) {
            this.setData({ deliveryType: options.deliveryType });
        }

        this.calculateTotal();
        this.loadAddressList();
    },
    // 切换配送方式
    // switchDeliveryType: function (e) {
    //     const type = e.currentTarget.dataset.type;
    //     this.setData({
    //         deliveryType: type
    //     });

    //     // 如果是自取，重置配送费
    //     if (type === 'pickup') {
    //         this.setData({ deliveryFee: 0 });
    //     } else {
    //         this.setData({ deliveryFee: 5 }); // 配送费5元
    //     }

    //     this.calculateTotal();
    // },
    selectSelf: function() {
        this.setData({
          deliveryType: 'pickup'
        });
      },
      
      selectDelivery: function() {
        this.setData({
          deliveryType: 'delivery'
        });
      },

    // 显示地址选择弹窗
    showAddressModal: function () {
        this.setData({
            showAddressModal: true
        });
    },

    // 隐藏地址选择弹窗
    hideAddressModal: function () {
        this.setData({
            showAddressModal: false
        });
    },

    // 获取微信地址
    getWechatAddress: function () {
        wx.chooseAddress({
            success: (res) => {
                const address = {
                    name: res.userName,
                    phone: res.telNumber,
                    fullAddress: `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}`
                };
                this.setData({
                    selectedAddress: address,
                    showAddressModal: false
                });
            },
            fail: (err) => {
                console.log('获取微信地址失败', err);
                wx.showToast({
                    title: '获取地址失败',
                    icon: 'none'
                });
            }
        });
    },

    // 跳转到新增地址页面
    goToAddAddress: function () {
        this.hideAddressModal();
        wx.navigateTo({
            url: '/pages/add-address/add-address'
        });
    },

    // 选择优惠券
    selectCoupon: function () {
        wx.showToast({
            title: '暂无可用优惠券',
            icon: 'none'
        });
    },

    // 输入备注
    onRemarkInput: function (e) {
        this.setData({
            remark: e.detail.value
        });
    },

    // 计算总价
    calculateTotal: function () {
        const products = this.data.products;
        let subTotal = 0;
        let totalQuantity = 0;

        products.forEach(item => {
            subTotal += item.price * item.quantity;
            totalQuantity += item.quantity;
        });

        const totalAmount = subTotal + this.data.deliveryFee;

        this.setData({
            subTotal: subTotal.toFixed(2),
            totalQuantity: totalQuantity,
            totalAmount: totalAmount.toFixed(2)
        });
    },

    // 加载地址列表
    loadAddressList: function () {
        // 这里应该从缓存或服务器获取地址列表
        const addressList = wx.getStorageSync('addressList') || [];
        this.setData({ addressList });

        // 设置默认地址
        const defaultAddress = addressList.find(addr => addr.isDefault) || addressList[0];
        if (defaultAddress) {
            this.setData({ selectedAddress: defaultAddress });
        }
    },

    // 处理支付
    handlePayment: function () {
        if (this.data.deliveryType === 'delivery' && !this.data.selectedAddress) {
            wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            });
            return;
        }

        const orderData = {
            deliveryType: this.data.deliveryType,
            products: this.data.products,
            address: this.data.selectedAddress,
            shopInfo: this.data.shopInfo,
            totalAmount: this.data.totalAmount,
            remark: this.data.remark
        };

        wx.showModal({
            title: '确认支付',
            content: `确认支付 ¥${this.data.totalAmount} 吗？`,
            success: (res) => {
                if (res.confirm) {
                    // 这里调用支付接口
                    this.processPayment(orderData);
                }
            }
        });
    },

    // 处理支付逻辑
    processPayment: function (orderData) {
        wx.showLoading({
            title: '支付中...',
        });

        // 模拟支付过程
        setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
                title: '支付成功',
                icon: 'success'
            });

            // 跳转到订单完成页面
            setTimeout(() => {
                wx.redirectTo({
                    url: '/pages/order-success/order-success'
                });
            }, 1500);
        }, 2000);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})